package com.b2b;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.b2b.model.GoodsDto;
import com.b2b.model.entity.User;
import com.b2b.model.entity.goods.Goods;
import com.b2b.model.receive.Good;
import com.b2b.service.UserService;
import com.b2b.util.ESconst;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@SpringBootTest
public class test {

    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;
    @Autowired
    UserService userService;

//    SearchRequest searchRequest = new SearchRequest("shop");
//    SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//    //分页
//        sourceBuilder.from(pageNo);
//        sourceBuilder.size(pageSize);
//    //精准匹配
//    MultiMatchQueryBuilder matchQuery = QueryBuilders.multiMatchQuery(shopSearch.getKeyWord(),"shopName","goodsType");
////        MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("shopName", keyword);
//        sourceBuilder.query(matchQuery);
//        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
//    //高亮
//    HighlightBuilder highlightBuilder = new HighlightBuilder();
//        highlightBuilder.field("title");
//        highlightBuilder.requireFieldMatch(false);
//        highlightBuilder.preTags("<span style='color:red'>");
//        highlightBuilder.postTags("</span>");
//        sourceBuilder.highlighter(highlightBuilder);
//
//        searchRequest.source(sourceBuilder);
//    SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
//
//    ArrayList<Map<String,Object>> list = new ArrayList<>();
//        for (SearchHit documentFields : search.getHits().getHits()) {
//
//        //解析高亮字段
//        Map<String, HighlightField> highlightFields = documentFields.getHighlightFields();
//        HighlightField title = highlightFields.get("title");
//        Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();//原来的结果
//        //解析
//        if (title!=null){
//            Text[] fragments = title.fragments();
//            String n_title = "";
//            for (Text text:fragments
//            ) {
//                n_title+=text;
//            }
//            sourceAsMap.put("title",n_title);
//        }
//
//
//        list.add(sourceAsMap);
//    }



    @Test
    void test1(){
        Object[] array = new Object[]{"JSON",1,2.2,true};
        List list = new ArrayList();
        list.add("first");
        list.add("secend");
        list.add("third");
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        jsonArray.add(array);
        jsonArray.add(list);
        jsonObject.put("1",list);
        String stringJson = "{1:111,2:111}";
        JSONObject object = JSON.parseObject(stringJson);
        System.out.println("object = " + object);
//        String jsonString = JSON.toJSONString(jsonObject);
//        System.out.println("jsonString = " + jsonString);
//        System.out.println("jsonObject = " + jsonObject);
//        System.out.println("jsonArray = " + jsonArray);
    }
    @Test
    void testCreateIndex() throws IOException {
        //创建索引
        CreateIndexRequest request = new CreateIndexRequest("goods");
        CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
        System.out.println(createIndexResponse);
    }
    @Test
    void testExistIndex() throws IOException {
        //判断索引存在
        GetIndexRequest getIndexRequest = new GetIndexRequest("deertest");
        boolean exists = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
        System.out.println(exists);
    }

    @Test
    void testDeleteIndex() throws IOException {
        //删除索引
        DeleteIndexRequest request = new DeleteIndexRequest("test4");

        AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
        System.out.println(delete.isAcknowledged());

    }

    //添加文档

    @Test
    void testAddDocument() throws IOException {
        Date date = new Date();
        System.out.println("date = " + date);
        User user = new User();
        user.setRegTime(date);
        IndexRequest request = new IndexRequest("shop");
        request.id("2");
        request.timeout(TimeValue.timeValueSeconds(1));
        //数据封入请求
        IndexRequest source = request.source(JSON.toJSONString(user), XContentType.JSON);
        //客户端发送请求  获取响应结果
        IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);

        String id = indexResponse.getId();
        System.out.println("indexResponse.toString() = " + indexResponse.toString());
        System.out.println("indexResponse.status() = " + indexResponse.status());

    }




    //获取文档判断存在  get/inedx/_doc/1
    @Test
    void testIsExists() throws IOException {
        GetRequest getRequest = new GetRequest("deertest", "1");
        //配置其他信息
        //不返回上下文
        getRequest.fetchSourceContext(new FetchSourceContext(false));
        boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
        System.out.println("exists = " + exists);
    }

    //获取文档信息
    @Test
    void testGetDocument() throws IOException {
        GetRequest getRequest = new GetRequest("goods", "40");
        GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
        String sourceAsString = getResponse.getSourceAsString();
        System.out.println("sourceAsString = " + sourceAsString);
    }


    //更新文档信息
    @Test
    void testUpdateDocument() throws IOException {
        String Id = "40";
        GetRequest getRequest = new GetRequest("goods", Id);
        GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
        Map<String, Object> goods = getResponse.getSourceAsMap();
        UpdateRequest updateRequest = new UpdateRequest("goods", Id);
        updateRequest.timeout("5s");
        goods.put("company",10001);
        UpdateRequest doc = updateRequest.doc(JSON.toJSONString(goods), XContentType.JSON);
        UpdateResponse updateResponse = client.update(doc, RequestOptions.DEFAULT);
        System.out.println(updateResponse);
    }





    //删除文档
    @Test
    void testDeleteDocument() throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest("goods", "49");
        deleteRequest.timeout("1s");
        DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
        System.out.println("deleteResponse = " + deleteResponse);

    }
    //大批量插入
    @Test
    void testBulkRequest() throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("5s");
        List<User> users = userService.selectAll();
        for (int i = 0; i < users.size(); i++) {
            bulkRequest.add(
                    new IndexRequest("deertest")
                            .id(""+i+1).source(JSON.toJSONString(users.get(i)),XContentType.JSON)
            );
        }
        BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println("bulkResponse = " + bulkResponse.hasFailures());
    }

    //查询
    @Test
    void testSearch() throws IOException {
        SearchRequest searchRequest = new SearchRequest(ESconst.ES_INDEX);
        //搜索条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //精确查询termQuery("username","孙尚香");
        //匹配所有matchAllQuery();
        TermQueryBuilder query = QueryBuilders.termQuery("username.keyword", "孙尚香");
        searchSourceBuilder.query(query);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        searchRequest.source(searchSourceBuilder);
        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        System.out.println("JSON.toJSONString(search.getHits()) = " + JSON.toJSONString(search.getHits()));
        System.out.println("-------此为分割线----------------此为分割线----------------此为分割线---------");
        for (SearchHit hit : search.getHits().getHits()) {
            System.out.println(hit.getSourceAsMap());
        }

    }
//    @Test
//    void getKey(){
//        String key = KeyUtil.keyUtils();
//        System.out.println("key = " + key);
//    }
}
